<template>
  <a-modal v-model:visible="showvisible" @cancel="showvisible = false" :mask-closable="false" :footer="false" title-align="start" title="详情" :width="1300">
    <a-scrollbar style="height: calc(100vh - 40px); overflow: auto; padding-bottom: 10px">
      <div class="publish-detail-con">
        <div class="left">
          <div class="tab-top">
            <a-tabs v-model:active-key="curTab">
              <a-tab-pane key="1" title="商品描述" />
              <a-tab-pane key="2" title="商品数据" />
            </a-tabs>
          </div>
          <!-- 商品描述 -->
          <div v-if="curTab === '1'" class="goods-desc mt10">
            <!-- 标题区域 -->
            <div class="title">
              <div class="more-language">
                <div @click="curLanguageTab == index" :class="[curLanguageTab == index ? 'active' : '']" v-for="(item, index) of languageList" :key="index">{{ item.name }}</div>
              </div>
              <div class="title-input">
                <div class="required">标题</div>
                <div class="base-style">
                  {{ form.title }}
                  <!-- <a-input disabled v-model="form.title" placeholder="请输入标题" /> -->
                </div>
                <div class="mt5">
                  <div class="flex-c">
                    <div class="required">固定链接：</div>
                    <div class="flex-c">
                      <span class="common-text" style="font-size: 14px">{{ domain }}{{ form.link }}</span>
                      <!-- <a-input style="width: 400px" v-model="form.link" placeholder="请输入固定链接" /> -->
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <!-- 商品简短描述 -->
            <div class="short-desc mt10">
              <div class="required">商品要点</div>
              <!-- <editor v-model="form.shortDesc" :height="200" :excludeKeys="['group-image', 'group-video', 'insertTable', 'codeBlock', 'emotion']" /> -->
              <div class="base-style">
                <div v-if="form.shortDesc" v-html="form.shortDesc"></div>
                <a-empty v-else></a-empty>
              </div>
            </div>
            <!-- 商品描述 -->
            <div class="desc mt10">
              <div class="required">描述</div>
              <!-- <editor v-model="form.desc" :height="200" /> -->
              <div class="base-style">
                <div v-if="form.desc" v-html="form.desc"></div>
                <a-empty v-else></a-empty>
              </div>
            </div>

            <!-- 商品标签 -->
            <div class="goods-tag mt10">
              <div>商品标签</div>

              <!-- <div class="tag-con mt5">
              <a-tag @click="selTag(item)" class="cursor mr5" v-if="tagList[0]" v-for="(item, index) of tagList" :key="index" color="arcoblue" bordered>{{ $extract(item, 'dataFromRestApi.name') }}</a-tag>
              <a-empty v-else description="暂无标签" />
            </div>
            <div class="mt10">已添加的标签</div>
            <div class="flex-c">
              <a-input style="width: 800px" v-model.trim="tagName" placeholder="批量添加请使用英文半角逗号隔开" />
              <a-button class="gray-outline ml5" @click="quickAddTag">添加</a-button>
            </div> -->
              <div class="tag-con mt5">
                <a-tag v-if="selTagList[0]" class="mr5" v-for="(item, index) of selTagList" :key="index" color="arcoblue" bordered>
                  <a-space>
                    <div>{{ item.name }}</div>
                    <!-- <div class="cursor" @click="selTagList.splice(index, 1)">
                    <icon-close />
                  </div> -->
                  </a-space>
                </a-tag>
                <a-empty v-else description="暂无标签" />
              </div>
            </div>
          </div>
          <!-- 商品数据 -->
          <div v-else class="goods-data">
            <!-- 商品类型 -->
            <div class="goods-type">
              <a-space>
                <div>类型</div>
                <div class="ml10">
                  <a-radio-group disabled v-model="form.goodsType">
                    <a-radio value="variable">变体</a-radio>
                  </a-radio-group>
                </div>
                <!-- <div>
                <span class="common-text">主体商品SKU：</span>
                <span>{{ subjectSku }}</span>
              </div> -->
              </a-space>
            </div>

            <div class="commodity-subject mb10">
              <div>
                <span>商品主体</span>
                <span class="common-text ml5" style="font-weight: 200">请选择ERP的产品SPU作为主体商品</span>
              </div>
              <div class="spu-info-con mt5">
                <a-select v-if="!spuInfo.id" :style="{ width: '180px' }" @change="handleChangeSku" :loading="searchSpuLoading" placeholder="请输入SPU" @search="handleSearch" allow-clear allow-search :filter-option="false" :show-extra-options="false">
                  <a-option v-for="(item, index) of spuList" :key="index" :label="item.spu" :value="item.id"></a-option>
                </a-select>
                <div class="clearfix sku-detail-con" style="font-size: 12px" v-else>
                  <div class="fl">
                    <ImgPopover :src="imgUrl(spuInfo)">
                      <template #con>
                        <a-image :preview="false" width="60" height="60" fit="contain" :src="imgUrl(spuInfo)" />
                      </template>
                    </ImgPopover>
                  </div>
                  <div class="fl" style="width: calc(100% - 80px); margin: 0 10px 0 10px">
                    <div>
                      <a-space>
                        <span class="common-text">SPU：</span>
                        <TextLimit position="top" :val="spuInfo.spu"></TextLimit>
                      </a-space>
                    </div>
                    <div style="margin-top: 5px">
                      <a-space>
                        <span class="common-text">名称：</span>
                        <TextLimit position="top" :val="spuInfo.spuName"></TextLimit>
                      </a-space>
                    </div>
                    <div style="margin-top: 5px">
                      <a-space>
                        <span class="common-text">类目：</span>
                        <span>{{ $extract(spuInfo, 'category.name') }}</span>
                        <span class="common-text ml10"> SKU数：</span>
                        <span>{{ spuInfo.productSkuList && spuInfo.productSkuList.length }}</span>
                      </a-space>
                    </div>
                  </div>

                  <!-- <div class="del-btn highlight cursor" @click="spuInfo = {}">
                  <icon-delete style="font-size: 20px" />
                </div> -->
                </div>
              </div>
            </div>

            <!-- 商品属性 -->
            <div class="goods-property mb10">
              <div class="required mb5">商品属性</div>
              <shopProperty type="edit" :isInfo="true" :list="attrList" :shopId="productInfo.shopId" @save="saveProperty" />
            </div>
            <!-- 商品变体 -->
            <div class="goods-variant">
              <div class="required mb5">商品变体</div>
              <productVariant ref="ProductVariant" type="edit" :isInfo="true" :spuInfo="spuInfo" :attList="attrList" :info="productInfo" :shopId="productInfo.shopId" />
            </div>
          </div>
          <!-- 保存按钮 -->
          <div class="flex-c-c" style="background-color: white; padding: 10px 0">
            <!-- <a-button type="primary" :loading="saveBasicInfoOrgoodsDataLoading" @click="saveBasicInfoOrgoodsData">保存</a-button> -->
            <!-- <a-button type="primary" class="ml10">保存并提交审核</a-button> -->
          </div>
        </div>
        <div class="right">
          <div class="goods-status edit-info-box">
            <div class="top">
              <div>商品发布状态</div>
              <!-- <div>
              <a-button size="mini" type="primary" @click="savePublishStatus">保存</a-button>
            </div> -->
            </div>
            <div class="bottom">
              <div>
                <a-space>
                  <div style="width: 90px; text-align: right">可见性：</div>
                  <!-- <a-select style="width: 200px" v-model="goodsPublishForm.visiable" placeholder="请选择">
                  <a-option value="publish">公开</a-option>
                  <a-option value="private">私密</a-option>
                </a-select> -->
                  <div v-if="goodsPublishForm.visiable == 'publish'">公开</div>
                  <div v-if="goodsPublishForm.visiable == 'private'">私密</div>
                </a-space>
              </div>
              <div class="mt10">
                <a-space>
                  <div style="width: 90px; text-align: right">可见范围：</div>
                  <!-- <a-select style="width: 200px" v-model="goodsPublishForm.range" placeholder="请选择">
                  <a-option value="visible">商店页和搜索结果页</a-option>
                  <a-option value="catalog">仅商店页</a-option>
                  <a-option value="search">仅搜索结果页</a-option>
                  <a-option value="hidden">隐藏</a-option>
                </a-select> -->
                  <div v-if="goodsPublishForm.range == 'visible'">商店页和搜索结果页</div>
                  <div v-if="goodsPublishForm.range == 'catalog'">仅商店页</div>
                  <div v-if="goodsPublishForm.range == 'search'">仅搜索结果页</div>
                  <div v-if="goodsPublishForm.range == 'hidden'">隐藏</div>
                </a-space>
              </div>
              <div class="mt10">
                <a-space>
                  <div style="width: 90px; text-align: right">是否推荐：</div>
                  <!-- <a-radio-group v-model="goodsPublishForm.featured">
                  <a-radio :value="true">是</a-radio>
                  <a-radio :value="false">否</a-radio>
                </a-radio-group> -->
                  <div>{{ goodsPublishForm.featured ? '是' : '否' }}</div>
                </a-space>
              </div>
            </div>
          </div>
          <div class="goods-img edit-info-box mt10">
            <div class="top">
              <div>商品图片</div>
              <div>
                <!-- <a-button size="mini" type="primary" @click="saveProductImg">保存</a-button> -->
              </div>
            </div>
            <div class="bottom" style="padding: 10px">
              <!-- <div class="common-text">点击图片修改图片</div> -->
              <div class="master-img-con">
                <a-upload disabled :show-file-list="false" list-type="picture-card" action="/" :on-before-upload="(file) => beforeUplaod(file, 'master')">
                  <template #upload-button v-if="goodsImgForm.windowPicList[0]">
                    <img :src="$extract(goodsImgForm.windowPicList[0], 'src')" alt="" style="width: 200px; height: 200px" />
                  </template>
                </a-upload>
              </div>
              <div>
                <span>上传橱窗图</span>
                <span class="common-text ml5">拖动可排序</span>
              </div>
              <div class="product-img-box">
                <div class="box">
                  <div class="product-sort-con">
                    <div class="box-img-con" v-for="(item, index) of goodsImgForm.windowPicList" :key="index">
                      <div class="my-image" @click="showImgPre(index)">
                        <a-image :preview="false" :src="item.src" width="80" height="80" />
                      </div>
                    </div>
                  </div>
                  <!-- <div class="fl" style="width: 80px; height: 80px">
                  <a-upload class="fl" :show-file-list="false" list-type="picture-card" action="/" :on-before-upload="(file) => beforeUplaod(file, 'windowPic')" />
                </div> -->
                </div>
              </div>
            </div>
          </div>

          <div class="goods-category edit-info-box mt10">
            <div class="top">
              <div>商品类别</div>
              <!-- <div>
              <a-button size="mini" type="primary" @click="saveProductCategory">保存</a-button>
            </div> -->
            </div>
            <div class="bottom" style="padding-left: 10px">
              <div v-for="(item, index) of showDetailCategoryList" :key="index">{{ item.name }}</div>
            </div>
          </div>

          <!-- <div class="goods-brand edit-info-box mt10">
          <div class="top">
            <div>商品品牌</div>
            <div>
              <a-button size="mini" type="primary">保存</a-button>
            </div>
          </div>
          <div class="bottom" style="padding: 10px">
            <a-scrollbar style="max-height: 200px; overflow: auto">
              <a-radio-group direction="vertical">
                <a-radio :value="item.id" v-for="(item, index) of brandList" :key="index">{{ item.name }}</a-radio>
              </a-radio-group>
            </a-scrollbar>
          </div>
        </div> -->
        </div>
      </div>
    </a-scrollbar>

    <!-- 编辑属性 -->
    <!-- <editAttr v-if="showEditAttrModal" v-model="showEditAttrModal" :shopId="productInfo.shopId" :info="editAttrInfo" :type="editAttrType" :selAttList="attrList" @save="saveAttr" /> -->

    <a-image-preview-group v-model:visible="visible" v-model:current="current" infinite :srcList="goodsImgForm.windowPicList.map((e:any) => e.src)" />
  </a-modal>
</template>

<script lang="ts" setup>
  import { computed, ref, nextTick, onMounted } from 'vue'
  import { OSSUpload } from '@/utils/ossUpload'
  import { findChildrenArray } from '@/utils'
  import { getProductSPUList, versionGetById, listAllCategoryTreeByShopId, tagRollPage, getBrandList, batchTag, batchProduct, batchProductVariation, versionBatchUpdate } from '@/api/product'
  import { Message } from '@arco-design/web-vue'
  import { useRouter, useRoute } from 'vue-router'
  import editor from '@/components/wangeditor/editor.vue'
  import productVariant from './components/productVariant.vue'
  import shopProperty from './components/shopProperty.vue'
  // import editAttr from './components/editAttr.vue'
  import Sortable from 'sortablejs'
  import dayjs from 'dayjs'
  import _ from 'lodash-es'
  let props = defineProps(['modelValue', 'id'])
  let emits = defineEmits(['save', 'update:modelValue'])
  let showvisible = computed({
    get() {
      return props.modelValue
    },
    set(val) {
      emits('update:modelValue', val)
    },
  })
  const ProductVariant = ref()
  const router = useRoute()
  let curTab = ref('1')
  let editAttrType = ref('add')
  let editAttrInfo = ref({})
  let showEditAttrModal = ref(false)
  let saveBasicInfoOrgoodsDataLoading = ref(false)
  let subjectSku = ref('') // 主体SKU
  let curLanguageTab = ref(0) // 以后多语言切换的时候用户，暂时无用
  let languageList = ref([{ name: '英语' }])
  let attrList: any = ref([]) // 已选择的属性信息
  let domain = ref('') // 域名
  let productInfo: any = ref({}) // 编辑的商品信息
  let brandList: any = ref([]) //品牌信息
  let categoryList: any = ref([]) //分类信息
  let tagList: any = ref([]) //标签信息
  let selTagList: any = ref([]) // 已经选中的标签
  let selCateGoryIds: any = ref([]) // 选中的分类Id
  let expandedCateGoryIds: any = ref([]) // 默认展开的树Id
  let showDetailCategoryList = ref([])
  let form: any = ref({
    title: '', // 标题
    link: '', // 固定链接
    desc: '', //商品描述
    shortDesc: '', //商品简短描述
    goodsType: 'variable', // 商品类型
  })

  let goodsPublishForm = ref({
    visiable: 'publish', //可见性
    range: 'visible', //可见范围
    featured: false, //可见性
  })

  let goodsImgForm: any = ref({
    windowPicList: [],
    img: '',
  })

  let tagName = ref('') // 添加标签

  let current = ref(1)
  let visible = ref(false)
  let searchSpuLoading = ref(false)

  let spuList: any = ref([])
  let spuInfo: any = ref({}) // spu信息
  let selPropertyList: any = ref([])

  // 上传
  const beforeUplaod = async (file: File, type: string) => {
    const res: any = await OSSUpload(file)
    let obj = {
      src: res.url,
    }
    goodsImgForm.value.windowPicList.push(obj)
  }

  // 图片预览
  const showImgPre = (index: number) => {
    current.value = index
    visible.value = true
  }
  const imgUrl = (info: any) => {
    return info.productPicList[0]?.url || ''
  }

  const handleChangeSku = (val: string) => {
    let item = spuList.value.find((item: any) => item.id == val)
    if (item) {
      spuInfo.value = item
    } else {
      spuInfo.value = {}
    }
  }

  const handleSearch = async (value: string) => {
    if (value) {
      try {
        searchSpuLoading.value = true
        const res: any = await getProductSPUList({ keyword: value, searchType: 'exact', keywordType: 'spu' })
        spuList.value = res.data?.records || []
      } catch (error) {}
      searchSpuLoading.value = false
    } else {
      spuList.value = []
    }
  }

  // 初始化拖拽
  const rowDropProductImg = () => {
    const body: any = document.querySelector('.product-sort-con')
    if (!body) return
    Sortable.create(body, {
      animation: 200, // 定义排序动画的时间
      forceFallback: true,
      sort: true,
      handle: '.my-image',
      onEnd(evt: any) {
        goodsImgForm.value.windowPicList.splice(evt.newIndex, 0, goodsImgForm.value.windowPicList.splice(evt.oldIndex, 1)[0])
        var newArray = goodsImgForm.value.windowPicList.slice(0)
        goodsImgForm.value.windowPicList = []
        nextTick(() => {
          goodsImgForm.value.windowPicList = newArray
        })
      },
    })
  }

  // 显示编辑属性的弹框
  const showModal = (type: string, info?: any) => {
    editAttrType.value = type
    editAttrInfo.value = info
    showEditAttrModal.value = true
  }

  // 选择标签
  const selTag = (item: any) => {
    let index = selTagList.value.findIndex((e: any) => e.name == item.dataFromRestApi.name)
    if (index == -1) {
      let obj = {
        id: item.dataFromRestApi.id,
        name: item.dataFromRestApi.name,
        slug: item.dataFromRestApi.slug,
      }
      selTagList.value.push(obj)
    }
  }

  // 快速添加标签
  const quickAddTag = async () => {
    if (!tagName.value) return Message.error('请填写标签名称')
    let arr = tagName.value.split(',')
    let params: any = {
      param: {
        create: [],
      },
      shopId: productInfo.value.shopId,
    }
    arr.forEach((e) => {
      let obj = {
        name: e,
        description: '',
        slug: e,
      }
      params.param.create.push(obj)
    })

    const res: any = await batchTag(params)
    if (res) {
      tagName.value = ''
      getTag()
      selTagList.value = [...selTagList.value, ...params.param.create]
      Message.success('添加标签成功')
    }
  }

  const getDetail = async () => {
    debugger
    const res: any = await versionGetById({ id: props.id })
    if (res) {
      productInfo.value = res.data || {}
      // 回显标题
      form.value.title = productInfo.value.dataFromRestApi.name || ''
      form.value.desc = productInfo.value.dataFromRestApi.description || ''
      form.value.shortDesc = productInfo.value.dataFromRestApi.short_description || ''
      // 商品主题sku
      subjectSku.value = productInfo.value.dataFromRestApi.sku
      // 标签
      selTagList.value = productInfo.value.dataFromRestApi.tags || []
      // 属性反显
      attrList.value = productInfo.value.dataFromRestApi.attributes || []
      // 类目
      if (productInfo.value.dataFromRestApi.categories) {
        let arr = productInfo.value.dataFromRestApi.categories || []
        showDetailCategoryList.value = arr
        selCateGoryIds.value = arr.map((e: any) => e.id)
        expandedCateGoryIds.value = arr.map((e: any) => e.id)
      }
      // 商品发布状态
      goodsPublishForm.value = {
        visiable: productInfo.value.dataFromRestApi.status,
        range: productInfo.value.dataFromRestApi.catalog_visibility,
        featured: productInfo.value.dataFromRestApi.featured,
      }
      // 图片
      goodsImgForm.value.windowPicList = productInfo.value.dataFromRestApi.images || []
      // 将商品链接拆解放
      let url = productInfo.value.dataFromRestApi.permalink || ''
      if (url) {
        const regex = /product\//
        const parts = url.split(regex)
        domain.value = parts[0] + 'product/'
        form.value.link = parts[1]
      }

      // 查找spu详情
      await handleSearch(res.data.dataFromRestApi.sku)
      let item = spuList.value.find((item: any) => item.spu == res.data.dataFromRestApi.sku)
      if (item) {
        spuInfo.value = item
      } else {
        spuInfo.value = {}
      }
    }
  }

  const setNewTreeData = (data: any) => {
    data.forEach((item: any) => {
      item.title = item.dataFromRestApi.name
      item.key = item.dataFromRestApi.id
      if (!item.children[0]) item.children = null
      if (item.children) {
        setNewTreeData(item.children)
      }
    })
  }

  const getBrand = async () => {
    let params = {
      pageSize: 9999999,
    }
    const res: any = await getBrandList(params)
    brandList.value = res.data.records || []
  }
  const getTag = async () => {
    let params = {
      shopIdList: [productInfo.value.shopId],
      pageSize: 9999999,
    }
    const res: any = await tagRollPage(params)
    tagList.value = res.data.list || []
  }
  const getCategory = async () => {
    let params = {
      shopId: productInfo.value.shopId,
    }
    const res: any = await listAllCategoryTreeByShopId(params)
    categoryList.value = res.data || []
    setNewTreeData(categoryList.value)
  }

  // const saveAttr = (info: any) => {
  //   if (editAttrType.value == 'add') {
  //     info.forEach((e: any) => {
  //       let index = attrList.value.findIndex((item: any) => item.id == e.id)
  //       if (index != -1) {
  //         attrList.value.splice(index, 1, e)
  //       } else if (index == -1) {
  //         attrList.value.push(e)
  //       }
  //     })
  //   } else {
  //     let index = attrList.value.findIndex((item: any) => item.id == info.id)
  //     if (index != -1) {
  //       attrList.value.splice(index, 1, info)
  //     }
  //   }
  // }

  // 编辑基本数据
  const saveBasicInfoOrgoodsData = async () => {
    let data = _.cloneDeep(productInfo.value)
    if (curTab.value == '1') {
      data.dataFromRestApi.name = form.value.title
      data.dataFromRestApi.permalink = `${domain.value}${form.value.link}`
      data.dataFromRestApi.description = form.value.desc
      data.dataFromRestApi.short_description = form.value.shortDesc
      data.dataFromRestApi.tags = selTagList.value
      saveUpdataData(data)
    } else {
      // console.log(setSpuPriceRule(), data)
      // console.log(attrList.value, '属性', ProductVariant.value, '变体数据', spuInfo.value, 'spu信息')
      let priceArr = setSpuPriceRule() || []
      data.dataFromRestApi.meta_data = priceArr.meta_data
      data.dataFromRestApi.sku = spuInfo.value.spu
      data.dataFromRestApi.attributes = attrList.value
      data.variationList = ProductVariant.value.autoCreateTableList.map((e: any) => {
        e.dataFromRestApi = _.cloneDeep(e)
        return e
      })
      saveUpdataData(data)
    }
  }

  const setSpuPriceRule = () => {
    let priceRule = ProductVariant.value.salePriceForm || {}
    let ruleItem: any = {
      meta_data: productInfo.value?.dataFromRestApi?.meta_data || [],
    }
    //一口价 disable 阶梯价
    if (priceRule.priceType == 'disable') {
      if (priceRule.num <= 0) {
        Message.error('请输入起订量')
        return false
      }

      // 一口价规则
      let index = ruleItem.meta_data.findIndex((item: any) => item.key == 'wpcpq_enable')
      if (index == -1) {
        ruleItem.meta_data.push({ key: 'wpcpq_enable', value: 'disable' })
      } else {
        ruleItem.meta_data[index].value = 'disable'
      }
      let index1 = ruleItem.meta_data.findIndex((item: any) => item.key == 'min_quantity')
      if (index1 == -1) {
        ruleItem.meta_data.push({ key: 'min_quantity', value: priceRule.num })
      } else {
        ruleItem.meta_data[index1].value = priceRule.num
      }
    } else {
      // 阶梯价规则
      let arr: any = []
      priceRule.priceList.forEach((el: any) => {
        let obj = { quantity: el.startNum, price: el.price, text: '', endNum: el.endNum }
        arr.push(obj)
      })
      let index = ruleItem.meta_data.findIndex((item: any) => item.key == 'wpcpq_enable')
      if (index == -1) {
        ruleItem.meta_data.push({ key: 'wpcpq_enable', value: 'override' })
      } else {
        ruleItem.meta_data[index].value = 'override'
      }
      let index1 = ruleItem.meta_data.findIndex((item: any) => item.key == 'wpcpq_prices')
      let itemInfo = {
        apply: 'all',
        apply_val: '',
        layout: 'default',
        method: 'volume',
        role: 'all',
        tiers: arr,
      }

      if (index1 == -1) {
        ruleItem.meta_data.push({ key: 'wpcpq_prices', value: JSON.stringify(itemInfo) })
      } else {
        ruleItem.meta_data[index1].value = JSON.stringify(itemInfo)
      }
    }

    return ruleItem

    // variantList.forEach((e: any) => {
    // 如果有促销时间
    //   if (obj.salePlanTime[0]) {
    //     let start = obj.salePlanTime[0]
    //     let end = obj.salePlanTime[1]
    //     e.date_on_sale_from = dayjs(start).format('YYYY-MM-DDTHH:MM:ss')
    //     e.date_on_sale_from_gmt = dayjs(start).format('YYYY-MM-DDTHH:MM:ss')
    //     e.date_on_sale_to = dayjs(end).format('YYYY-MM-DDTHH:MM:ss')
    //     e.date_on_sale_to_gmt = dayjs(end).format('YYYY-MM-DDTHH:MM:ss')
    //   }

    //   // 看是否已经存在规则,存在修改，不存在新增
    //   let index = e.meta_data.findIndex((item: any) => item.key == 'wpcpq_enable')
    //   if (index == -1) {
    //     e.meta_data.push({ key: 'wpcpq_enable', value: 'disable' })
    //     let metaDataItem = { key: 'min_quantity', value: obj.num }
    //     e.meta_data.push(metaDataItem)
    //   } else {
    //     e.meta_data[index].value = 'disable'
    //     let valuIndex = e.meta_data.findIndex((item: any) => item.key == 'min_quantity')
    //     if (valuIndex == -1) {
    //       let metaDataItem = { key: 'min_quantity', value: obj.num }
    //       e.meta_data.push(metaDataItem)
    //     } else {
    //       e.meta_data[valuIndex].value = obj.num
    //     }
    //   }
    //   // })
    // } else {
    //   // variantList.forEach((e: any) => {
    //   let arr: any = []
    //   obj.priceList.forEach((el: any) => {
    //     let obj = { quantity: el.startNum, price: el.price, text: '', endNum: el.endNum }
    //     arr.push(obj)
    //   })
    //   // 看是否已经存在规则,存在修改，不存在新增
    //   let index = e.meta_data.findIndex((item: any) => item.key == 'wpcpq_enable')
    //   if (index == -1) {
    //     e.meta_data.push({ key: 'wpcpq_enable', value: 'override' })
    //     let metaDataItem: any = { key: 'wpcpq_prices', value: JSON.stringify({ tiers: arr }) }
    //     e.meta_data.push(metaDataItem)
    //   } else {
    //     e.meta_data[index].value = 'override'
    //     let valuIndex = e.meta_data.findIndex((item: any) => item.key == 'wpcpq_prices')
    //     if (valuIndex == -1) {
    //       let metaDataItem: any = { key: 'wpcpq_prices', value: JSON.stringify({ tiers: arr }) }
    //       e.meta_data.push(metaDataItem)
    //     } else {
    //       e.meta_data[valuIndex].value = JSON.stringify({ tiers: arr })
    //     }
    //   }
    //   // })
    // }
    // return true
  }

  // 商品发布状态
  const savePublishStatus = async () => {
    let data = _.cloneDeep(productInfo.value)
    data.dataFromRestApi.catalog_visibility = goodsPublishForm.value.range
    data.dataFromRestApi.status = goodsPublishForm.value.visiable
    data.dataFromRestApi.featured = goodsPublishForm.value.featured
    saveUpdataData(data)
  }
  // 商品图片
  const saveProductImg = async () => {
    let data = _.cloneDeep(productInfo.value)
    data.dataFromRestApi.images = goodsImgForm.value.windowPicList
    saveUpdataData(data)
  }
  // 商品分类
  const saveProductCategory = async () => {
    let arr: any = []
    let data = _.cloneDeep(productInfo.value)
    selCateGoryIds.value.forEach((e: any) => {
      let item = findChildrenArray(categoryList.value, e, 'key')
      let obj = {
        name: item.dataFromRestApi.name,
        slug: item.dataFromRestApi.slug,
        id: item.dataFromRestApi.id,
      }
      arr.push(obj)
    })

    data.dataFromRestApi.categories = arr
    saveUpdataData(data)
  }

  // 选择属性
  const saveProperty = (list: any) => {
    attrList.value = list
  }

  // 编辑数据调用的公共接口方法
  const saveUpdataData = async (data: any) => {
    let params = {
      createOrUpdateDocList: [data],
    }
    const res: any = await versionBatchUpdate(params)
    if (res) {
      Message.success('保存成功')
      getDetail()
    }
  }

  onMounted(async () => {
    // rowDropProductImg()
    await getDetail() //获取商品详情
    await getBrand() //获取商品品牌
    await getTag() //获取商品标签
    await getCategory() //获取商品类目
  })
</script>

<style lang="less" scoped>
  .base-style {
    padding: 4px 10px;
    line-height: 20px;
    border: 1px solid #d7d7d7;
  }
  .publish-detail-con {
    display: flex;
    .left {
      width: 75%;
      .tab-top {
        background-color: white;
      }
      .goods-desc {
        .title {
          .more-language {
            display: flex;
            margin-left: 20px;
            div {
              padding: 5px;
              background-color: #dddddd;
              margin-left: 10px;
              border-top-left-radius: 3px;
              border-top-right-radius: 3px;
              font-size: 12px;
              color: #7f7f7f;
            }
            .active {
              color: #333333;
              background-color: white;
            }
          }
          .title-input {
            width: 100%;
            padding: 5px 10px;
            background-color: white;
          }
        }
        .desc,
        .short-desc {
          width: 100%;
          padding: 5px 10px;
          background-color: white;
        }

        .goods-tag {
          width: 100%;
          background-color: white;
          padding: 5px 10px;
        }
      }
      .goods-data {
        .goods-type {
          width: 100%;
          background-color: white;
          padding: 10px 20px;
          margin: 10px 0;
        }
        .goods-main-body {
          width: 100%;
          background-color: white;
          padding: 10px 20px;
          .spu-info-con {
            min-height: 80px;
            width: 100%;
            border: 1px solid #d7d7d7;
            padding: 5px;
            box-sizing: border-box;
            border-radius: 5px;

            .sku-detail-con {
              position: relative;
              .del-btn {
                position: absolute;
                right: 10px;
                top: 10px;
              }
            }
          }
        }
        .goods-property,
        .goods-variant {
          width: 100%;
          background-color: white;
          padding: 10px 20px;
        }
      }
    }
    .right {
      flex: 1;
      margin-left: 10px;
      margin-right: 15px;
      .goods-status,
      .edit-info-box {
        .top {
          display: flex;
          justify-content: space-between;
          align-items: center;
          background: #d7d7d7;
          padding: 5px 15px 5px 10px;
          box-sizing: border-box;
        }
        .bottom {
          background-color: white;
          padding: 10px 0;
          box-sizing: border-box;
        }
      }

      .goods-img {
        .master-img-con {
          text-align: center;
          padding: 10px;
          box-sizing: border-box;
          // border: 1px solid #d7d7d7;
          :deep(.arco-upload-picture-card) {
            width: 200px;
            height: 200px;
          }
          :deep(.arco-upload-list-picture) {
            width: 200px;
            height: 200px;
          }
        }
        .product-img-box {
          overflow: hidden;
          .box {
            margin-top: 5px;
            // min-height: 180px;
            // border-right: 1px solid #d7d7d7;
            .box-img-con {
              float: left;
              width: 80px;
              height: 80px;
              position: relative;
              margin: 0 10px 10px 0;

              .mask {
                height: 20px;
                width: 80px;
                position: absolute;
                bottom: 0;
                left: 0;
                // display: none;
                z-index: 1;
                background: rgba(0, 0, 0, 0.5);
                .btn-con {
                  width: 80px;
                  color: white;
                  font-size: 14px;
                  text-align: center;
                  // margin-top: 5px;
                  align-items: center;
                }
              }
            }
          }
        }
      }
    }
  }

  .commodity-subject {
    background-color: white;
    padding: 10px 20px;
    .spu-info-con {
      min-height: 80px;
      width: 100%;
      border: 1px solid #d7d7d7;
      padding: 5px;
      box-sizing: border-box;
      border-radius: 5px;

      .sku-detail-con {
        position: relative;
        .del-btn {
          position: absolute;
          right: 10px;
          top: 10px;
        }
      }
    }
  }
</style>
